/*
 * Copyright (C),2015,北京新诺创科软件技术有限公司
 * author zhangmengliang
 */
package com.xnck.mfpms.interceptor;

import com.xnck.mfpms.annotation.NeedMenu;
import com.xnck.mfpms.service.MenuService;
import com.xnck.mfpms.util.SessionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class MenuInterceptor extends HandlerInterceptorAdapter {
    protected static final Logger log = Logger.getLogger(MenuInterceptor.class);

    @Autowired
    private MenuService menuService;

    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {

    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView view) throws Exception {
        //如果拦截的是方法，查验是否有NeedMeun注解，如果有注解则需要验证用户是否已登录
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            NeedMenu needMeun = method.getMethodAnnotation(NeedMenu.class);
            if (null == needMeun || needMeun.validate() == false) {
                return;
            }
            if (null != view) {
                try {
                    String curUserId = SessionUtils.getCurrentUserId(request);
                    Map<String, Object> map = menuService.getsByUserId(curUserId);
                    view.addObject("menus", map);
                } catch (Exception e) {
                    log.error(e.toString());
                }
            }
        }
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }
}
